package com.net.okhttphelper.http;

import android.net.ParseException;

import com.net.okhttphelper.constant.ErrorEnum;

import org.json.JSONException;

import java.io.FileNotFoundException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

/**
 * 网络请求错误处理
 * @author jie
 */
public class ExceptionHandle {

    /**
     * 处理网络请求错误
     */
    public static void handleException(Throwable e, DataCallBack listener) {
        if (e instanceof UnknownHostException || e instanceof ConnectException) {
            listener.fail(ErrorEnum.ERROR_NO_NET.getCode(), ErrorEnum.ERROR_NO_NET.getMessage());
        } else if (e instanceof SocketTimeoutException) {
            listener.fail(ErrorEnum.ERROR_SOCKET_TIME_OUT.getCode(), ErrorEnum.ERROR_SOCKET_TIME_OUT.getMessage());
        } else if (e instanceof JSONException
                || e instanceof ParseException
                || e instanceof NullPointerException) {
            listener.fail(ErrorEnum.ERROR_PARSE.getCode(), ErrorEnum.ERROR_PARSE.getMessage());
        } else if (e instanceof FileNotFoundException) {
            listener.fail(ErrorEnum.ERROR_FILE_NO_EXIST.getCode(), ErrorEnum.ERROR_FILE_NO_EXIST.getMessage());
        } else {
            listener.fail(ErrorEnum.ERROR_FAIL.getCode(), ErrorEnum.ERROR_FAIL.getMessage());
        }
    }

    /**
     * 将服务器返回的错误进行中文提示信息转换
     * @param e 服务器返回的错误
     * @return 转换后的中文提示错误
     */
    public static String handlerException(Throwable e) {
        String msg;
        if (e instanceof UnknownHostException || e instanceof ConnectException) {
            msg = ErrorEnum.ERROR_NO_NET.getMessage();
        } else if (e instanceof SocketTimeoutException) {
            msg = ErrorEnum.ERROR_SOCKET_TIME_OUT.getMessage();
        } else if (e instanceof JSONException
                || e instanceof ParseException
                || e instanceof NullPointerException
                || e instanceof NumberFormatException) {
            msg = ErrorEnum.ERROR_PARSE.getMessage();
        } else if (e instanceof FileNotFoundException) {
            msg = ErrorEnum.ERROR_FILE_NO_EXIST.getMessage();
        } else {
            msg = ErrorEnum.ERROR_FAIL.getMessage();
        }
        return msg;
    }

}
